package gui.Main;

import gui.newWindows.JoinWindow;
import hypeerweb.HyPeerWebSegment;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.InetAddress;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import network.GlobalObjectId;
import network.ObjectDB;
import network.PeerCommunicator;
import network.PortNumber;

/**
 * The central GUI used to display information about the HyPeerWeb and debug information
 * 
 * @author Matthew Smith
 */
public class GUI extends JFrame {
	private static GUI singleton = null;
	private static JoinWindow startWindow;
	/** Main Debugger Panel **/
	private HyPeerWebDebugger debugger;
	private static GUI main;
	private HyPeerWebSegment hypeerweb;
	private JScrollPane scrollPane;
	
	/**
	 * Creates and initializes the GUI as being the root
	 */
	public GUI() {
		this.setTitle("HyPeerWeb DEBUGGER V 1.1");

		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});

		debugger = new HyPeerWebDebugger(this);
		scrollPane = new JScrollPane(debugger);
		scrollPane.setPreferredSize(new Dimension(debugger.WIDTH + 20, debugger.HEIGHT));
		
		this.getContentPane().add(scrollPane);
		this.pack();
	}
	
	public void populate(HyPeerWebSegment hypeerweb) {
		this.hypeerweb = hypeerweb;
		hypeerweb.addGUI(new GUICore());
		debugger.populate();
	}

	public static GUI getSingleton() {
		if (singleton == null) {
			try {
				singleton = new GUI();
				singleton.setVisible(true);
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
				// hypeerweb.close();
				System.exit(1);
			}
		}
		
		return singleton;
	}

	/**
	 * Start Point of the Program
	 */
	public static void main(String[] args) {
		PortNumber num = PortNumber.getApplicationsPortNumber();
		PeerCommunicator.createPeerCommunicator(PortNumber
				.getApplicationsPortNumber());
		PortNumber num2 = PortNumber.getApplicationsPortNumber();
		getSingleton();
	}

	public static void setMain(GUI temp) {
		System.out.println("set main");
		main = temp;
	}

	/**
	 * Retrieves the HyPeerWeb Debugging Panel
	 * 
	 * @return HyPeerWebDebugger
	 */
	public HyPeerWebDebugger getHyPeerWebDebugger() {
		return debugger;
	}

	public HyPeerWebSegment getHyPeerWeb() {
		return hypeerweb;
	}

	public void printToTracePanel(Object msg) {
		debugger.getTracePanel().print(msg);
	}

	public void printToDebugPanel(Object msg) {
		debugger.getStatus().setContent((String) msg);
	}

	public void finalize() {
		hypeerweb.close();
	}

}
